// pages/guidanceStudy/latest_banner/banner.js

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner_info: [],
    //切换的参数
    swiper_data: {
      current: 1,
      total: 3
    },
    btn_swiper: [],
    swiper_img: [],
    active_class: 0,
    //当前数据
    active_list:{},
    animationData: {},
    animationData2: {},
    ratio: app.phoneInfo.ratio,
    alertType: false,
    second: 10,
    submitType: true,
    local_policy_id: '',
    disabled: true,
    name: '',
    phone: '',
    code: '',
    codeText: '获取验证码',
    isGetCode: true,
    codeColor: '#e63939',
    shareTempFilePath: '',
    showDialog: false
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '拼命加载中...',
      icon: 'none'
    });
    this.stretch(350) ; 
    this.shrink(250) ;
    this.setData({
      'swiper_data.current': options.current
    })

    wx.request({
      url: app.globalData.url + 'c=activity&m=shareList&user_id=' + wx.getStorageSync('user_id'),
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status === 200) {
          var btn_swiper = [];
          for (var i = 0; i < res.data.activity_info.length; i++){
            btn_swiper.push({
              id: i,
              sverType: false
            })
          }
          this.setData({
            'swiper_data.total': res.data.activity_info.length,
            'swiper_img': res.data.activity_info,
            'active_list': res.data.activity_info[options.current-1],
            'btn_swiper': btn_swiper
          })
        }
      },
      fail: res => {
        wx.hideLoading();
        wx.showToast({
          title: res.msg
        });
      },
    });
  },
  /**
   * 切换时 获取到的数据
   */
  imgchange(event) {
    this.setData({
      'swiper_data.current': event.detail.current + 1,
      'active_list': this.data.swiper_img[event.detail.current] 
    });
    this.stretch(350)
    this.shrink(250)
  },
  // 收缩
  stretch(h) {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.height(h).step()
    this.setData({
      animationData: animation.export(),
    })
  },
  // 展开
  shrink(h) {
    var animation2 = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation2 = animation2
    animation2.height(h).step()
    this.setData({
      animationData2: animation2.export()
    })
  },

  /**
 * 获取图片
 */
  getImage: function () {
    wx.getImageInfo({
      src: this.data.active_list.poster_image,
      success: img1 => {
        wx.getImageInfo({
          src: this.data.active_list.qr_code_url,
          success: img2 => {
            // console.log(img1);
            // console.log(img2);
            this.drawImg(img1, img2);
          },
          fail: () => {
            wx.hideLoading();
          }
        })
      },
      fail: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * 点击图片
   */
  openImg(e){
    wx.navigateTo({
      url: '/pages/guidanceStudy/latest_open/open?poster_image=' + this.data.active_list.poster_image + '&qr_code_url=' + this.data.active_list.qr_code_url + '&barTitle=' + this.data.active_list.title
    });
  },

  /**
   * 保存分享福利券
   */
  submit: function () {
    wx.showLoading({
      title: '保存中',
    });
    this.getImage() ;
  },
  /**
   * canvas绘制
   */
  drawImg: function (img1, img2) {
    var context = wx.createCanvasContext('share');
    context.fillStyle = '#F1F1F1';
    context.shadowColor = "#E5E5E5";
    context.fillRect(0, 0, 640 / this.data.ratio, 1138 / this.data.ratio);

    let canvasWidthPx = 640 / this.data.ratio;
    let canvasHeightPx = 1138 / this.data.ratio;
    context.drawImage(img1.path, 0, 0, canvasWidthPx, canvasHeightPx);

    let img2X = (640 - img2.width) / this.data.ratio / 2;
    let img2Y = 850 / this.data.ratio;
    context.drawImage(img2.path, img2X, img2Y, img2.width / this.data.ratio, img2.height / this.data.ratio);

  
    context.draw(false, this.getTempFilePath);
  },

  /**
   * 获取临时路径
   */
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'share',
      success: res => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
        this.saveImageToPhotosAlbum();
      }
    })
  },

  /**
   * 保存相册
   */
  saveImageToPhotosAlbum: function () {
    wx.hideLoading();
    var that = this;
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.getSetting({
      success(res) {
        // console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.save();
            },
            fail(err) {
              // console.log(err);
              that.setData({
                'showDialog': true
              })
            }
          })
        } else {
          that.save();
        }
      }
    })
  },

  save: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        this.setData({
          alertType: true
        })
        this.waitTime();
      },
      fail: (err) => {
        // console.log(err);
      }
    })
  },

  /**
   * 倒计时
   */
  waitTime: function () {
    let s = this.data.second;
    var timer = setInterval(() => {
      s--;
      if (s == 0) {
        clearInterval(timer);
        timer = null;
        this.setData({
          submitType: false
        })
      } else {
        this.setData({
          second: s
        });
      }
    }, 1000);

    // setTimeout(this.waitTime, 1000);
  },

  /**
   * 关闭弹窗
   */
  closeAlert: function () {
    var btn_swiper = this.data.btn_swiper
    for (var i = 0; i < btn_swiper.length; i++){
      if ((this.data.swiper_data.current - 1) === i){
        btn_swiper[i].sverType = true
      }
    }
    this.setData({
      alertType: false,
      submitType: true,
      sverType: true,
      second: 10,
      btn_swiper: btn_swiper
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})